<template>
  <div class="timer-container" :class="{ 'floating': isFloating }">
    <!-- 计时器显示区域 -->
    <div class="timer-display" :style="{ backgroundColor: backgroundColor, color: textColor }">
      <div class="time-text">{{ formattedTime }}</div>
      <div class="millisecond-text" v-if="showMilliseconds">{{ millisecondsText }}</div>
    </div>
    
    <!-- 悬浮状态下的取消按钮 -->
    <div class="float-cancel" v-if="isFloating">
      <button @click="toggleFloating" class="float-btn">取消悬浮</button>
    </div>
    
    <!-- 控制按钮区域 -->
    <div class="controls" v-if="!isFloating">
      <!-- 模式切换 -->
      <div class="mode-switch">
        <button :class="{ active: mode === 'countdown' }" @click="setMode('countdown')">倒计时</button>
        <button :class="{ active: mode === 'stopwatch' }" @click="setMode('stopwatch')">正计时</button>
      </div>
      
      <!-- 倒计时设置 -->
      <div class="countdown-settings" v-if="mode === 'countdown'">
        <div class="preset-buttons">
          <button @click="setPreset(1)">1分钟</button>
          <button @click="setPreset(5)">5分钟</button>
          <button @click="setPreset(10)">10分钟</button>
        </div>
        <div class="countdown-settings-row">
          <div class="time-input">
            <span class="time-label">时间设置:</span>
            <div class="time-input-group">
              <input type="number" v-model.number="hours" min="0" max="23" placeholder="时" @wheel="handleWheel($event, 'hours')">
              <span class="time-unit">时</span>
            </div>
            <div class="time-input-group">
              <input type="number" v-model.number="minutes" min="0" max="59" placeholder="分" @wheel="handleWheel($event, 'minutes')">
              <span class="time-unit">分</span>
            </div>
            <div class="time-input-group">
              <input type="number" v-model.number="seconds" min="0" max="59" placeholder="秒" @wheel="handleWheel($event, 'seconds')">
              <span class="time-unit">秒</span>
            </div>
          </div>
          <!-- 倒计时提醒设置 -->
          <div class="settings">
            <div class="setting-item">
              <label>
                <input type="checkbox" v-model="showMilliseconds">
                显示毫秒
              </label>
            </div>
            <div class="setting-item">
              <label>
                <input type="checkbox" v-model="enableNotification">
                通知提醒
              </label>
            </div>
            <div class="setting-item">
              <label>
                <input type="checkbox" v-model="enableSound">
                提示音
              </label>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 正计时直接开始 -->
      <div class="stopwatch-settings" v-if="mode === 'stopwatch'">
        <!-- 正计时提醒设置 -->
        <div class="settings stopwatch-settings-row">
          <div class="setting-item">
            <label>
              <input type="checkbox" v-model="showMilliseconds">
              显示毫秒
            </label>
          </div>
        </div>
      </div>
      
      <!-- 控制按钮 -->
      <div class="control-buttons">
        <template v-if="!isFloating">
          <button v-if="!isRunning" @click="startTimer" class="start-btn">开始计时</button>
          <button v-if="isRunning" @click="pauseTimer" class="pause-btn">暂停</button>
          <button v-if="isRunning || timeElapsed > 0" @click="resetTimer" class="reset-btn">重置</button>
          <button @click="toggleFloating" class="float-btn">悬浮</button>
        </template>
        <template v-else>
          <button @click="toggleFloating" class="float-btn">取消悬浮</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'

// 响应式数据
const mode = ref('countdown') // 'countdown' 或 'stopwatch'
const isRunning = ref(false)
const isFloating = ref(false)
const timeElapsed = ref(0) // 已经过的时间（毫秒）
const countdownTime = ref(0) // 倒计时总时间（毫秒）
const showMilliseconds = ref(false)
const enableNotification = ref(false)
const enableSound = ref(false)

// 时间输入
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)

// 样式设置
const backgroundColor = ref('#6b7280') // 灰色
const textColor = ref('#ffffff') // 白色

// 定时器引用
let timerInterval = null

// 计算属性
const formattedTime = computed(() => {
  let totalMilliseconds = 0
  if (mode.value === 'countdown') {
    totalMilliseconds = Math.max(0, countdownTime.value - timeElapsed.value)
  } else {
    totalMilliseconds = timeElapsed.value
  }
  
  const totalSeconds = Math.floor(totalMilliseconds / 1000)
  const h = Math.floor(totalSeconds / 3600)
  const m = Math.floor((totalSeconds % 3600) / 60)
  const s = totalSeconds % 60
  
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
})

const millisecondsText = computed(() => {
  let totalMilliseconds = 0
  if (mode.value === 'countdown') {
    totalMilliseconds = Math.max(0, countdownTime.value - timeElapsed.value)
  } else {
    totalMilliseconds = timeElapsed.value
  }
  
  const ms = Math.floor(totalMilliseconds % 1000)
  return ms.toString().padStart(3, '0')
})

// 方法
const setMode = (newMode) => {
  mode.value = newMode
  resetTimer()
}

const setPreset = (minutesValue) => {
  hours.value = 0
  minutes.value = minutesValue
  seconds.value = 0
  setCustomTime()
}

const setCustomTime = () => {
  const totalMilliseconds = ((hours.value || 0) * 3600 + 
                            (minutes.value || 0) * 60 + 
                            (seconds.value || 0)) * 1000
  countdownTime.value = totalMilliseconds
  timeElapsed.value = 0
}

// 新增方法：设置并立即开始倒计时
const setAndStart = (minutesValue) => {
  setPreset(minutesValue)
  startTimer()
}

// 新增方法：设置自定义时间并立即开始
const setCustomTimeAndStart = () => {
  setCustomTime()
  startTimer()
}

// 处理鼠标滚轮事件
const handleWheel = (event, field) => {
  event.preventDefault()
  const delta = event.deltaY > 0 ? -1 : 1
  if (field === 'hours') {
    hours.value = Math.max(0, Math.min(23, (hours.value || 0) + delta))
  } else if (field === 'minutes') {
    minutes.value = Math.max(0, Math.min(59, (minutes.value || 0) + delta))
  } else if (field === 'seconds') {
    seconds.value = Math.max(0, Math.min(59, (seconds.value || 0) + delta))
  }
}

const startTimer = () => {
  if (!isRunning.value) {
    isRunning.value = true
    const startTime = Date.now() - timeElapsed.value
    timerInterval = setInterval(() => {
      const now = Date.now()
      timeElapsed.value = now - startTime
      
      // 检查倒计时是否结束
      if (mode.value === 'countdown' && countdownTime.value > 0 && timeElapsed.value >= countdownTime.value) {
        timeElapsed.value = countdownTime.value
        pauseTimer()
        if (enableNotification.value) {
          showNotification()
        }
        if (enableSound.value) {
          playSound()
        }
      }
    }, 10)
  }
}

const pauseTimer = () => {
  if (isRunning.value) {
    isRunning.value = false
    clearInterval(timerInterval)
  }
}

const resetTimer = () => {
  pauseTimer()
  timeElapsed.value = 0
  if (mode.value === 'countdown') {
    // 重置为默认1分钟
    hours.value = 0
    minutes.value = 1
    seconds.value = 0
    setCustomTime()
  }
}

const toggleFloating = () => {
  isFloating.value = !isFloating.value
  // 检查是否在 uTools 环境中运行
  if (typeof window.utools !== 'undefined' && window.utools) {
    if (isFloating.value) {
      // 设置为悬浮窗口
      window.utools.setExpendHeight(80)
    } else {
      // 恢复正常窗口
      window.utools.setExpendHeight(400)
    }
  }
}

const showNotification = () => {
  // 检查是否在 uTools 环境中运行
  if (typeof window.utools !== 'undefined' && window.utools) {
    // 在 uTools 中使用系统通知
    window.utools.showNotification('时间到了！')
  } else if ('Notification' in window) {
    // 在浏览器中使用 Web Notifications
    new Notification('计时器提醒', {
      body: '时间到了！',
      icon: '/logo.png'
    })
  }
}

const playSound = () => {
  try {
    const audioContext = new (window.AudioContext || window.webkitAudioContext)()
    const oscillator = audioContext.createOscillator()
    const gainNode = audioContext.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)
    
    oscillator.type = 'sine'
    oscillator.frequency.value = 800
    gainNode.gain.value = 0.3
    
    oscillator.start()
    setTimeout(() => {
      oscillator.stop()
    }, 500)
  } catch (e) {
    console.log('无法播放提示音:', e)
  }
}

// 监听时间变化，用于调试
watch(timeElapsed, (newVal) => {
  // 可以在这里添加调试信息
})

// 监听时间输入值的变化，实时更新倒计时总时间
watch([hours, minutes, seconds], () => {
  // 只在倒计时模式且未运行时实时更新
  if (mode.value === 'countdown' && !isRunning.value) {
    setCustomTime()
  }
})

// 组件挂载和卸载时的处理
onMounted(() => {
  // 初始化为1分钟倒计时
  minutes.value = 1
  setCustomTime()
  
  // 请求通知权限
  if ('Notification' in window && Notification.permission === 'default') {
    Notification.requestPermission()
  }
  
  // 监听插件进入事件
  if (typeof window.utools !== 'undefined' && window.utools) {
    window.utools.onPluginEnter((action) => {
      console.log('进入计时器插件', action)
    })
  }
})

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
})
</script>

<style scoped>
.timer-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-family: 'Arial', sans-serif;
}

.timer-container.floating {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 9999;
  width: 200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  overflow: hidden;
  padding-top: 30px;
  box-sizing: border-box;
}

.timer-container.floating .controls {
  padding: 10px;
}

.float-cancel {
  display: flex;
  justify-content: center;
  padding: 10px;
  background-color: #f9fafb;
}

.timer-container.floating .float-cancel {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 0;
  background-color: transparent;
}

.timer-container.floating .float-cancel .float-btn {
  padding: 4px 8px;
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 4px;
}

.timer-display {
  padding: 20px;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80px;
}

.time-text {
  font-size: 28px;
  letter-spacing: 2px;
}

.millisecond-text {
  font-size: 14px;
  opacity: 0.8;
  margin-top: 4px;
  letter-spacing: 1px;
}

.controls {
  padding: 20px;
  background-color: #f9fafb;
  flex: 1;
}

.mode-switch {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.mode-switch button {
  flex: 1;
  padding: 8px 16px;
  border: 1px solid #d1d5db;
  background-color: #f9fafb;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  color: #374151;
}

.mode-switch button.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.countdown-settings {
  margin-bottom: 20px;
}

.countdown-settings-row {
  display: flex;
  gap: 20px;
  align-items: center;
  margin-top: 15px;
  justify-content: space-between;
  flex-wrap: wrap;
}

.stopwatch-settings {
  margin-bottom: 20px;
  text-align: center;
}

.stopwatch-settings-row {
  justify-content: center;
  margin-bottom: 15px;
}

.stopwatch-settings .start-btn {
  padding: 10px 20px;
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
}

.preset-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.preset-buttons button {
  flex: 1;
  padding: 8px;
  border: 1px solid #d1d5db;
  background-color: #f9fafb;
  border-radius: 4px;
  cursor: pointer;
  color: #374151;
}

.time-input {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.time-input-group {
  display: flex;
  align-items: center;
  gap: 2px;
}

.time-label {
  font-weight: bold;
  color: #374151;
  white-space: nowrap;
}

.time-input input {
  width: 60px;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  text-align: center;
  background-color: #ffffff;
  color: #374151;
}

.time-unit {
  color: #374151;
  font-weight: bold;
  margin-left: 2px;
}

.time-input button {
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.time-input .start-btn {
  background-color: #10b981;
}

.time-input input {
  width: 60px;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  text-align: center;
  background-color: #ffffff;
  color: #374151;
}

.time-input button {
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.time-input .start-btn {
  background-color: #10b981;
}

.control-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.control-buttons button {
  flex: 1;
  min-width: 80px;
  padding: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  color: #ffffff;
}

.start-btn {
  background-color: #10b981;
  color: white;
}

.pause-btn {
  background-color: #f59e0b;
  color: white;
}

.reset-btn {
  background-color: #ef4444;
  color: white;
}

.float-btn {
  background-color: #6366f1;
  color: white;
}

.timer-container.floating .control-buttons {
  justify-content: center;
}

.timer-container.floating .control-buttons button {
  min-width: auto;
  padding: 8px 12px;
  font-size: 14px;
}

.settings {
  display: flex;
  gap: 15px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.setting-item {
  display: flex;
  align-items: center;
}

.settings label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  white-space: nowrap;
}

.settings input[type="checkbox"] {
  width: 16px;
  height: 16px;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .control-buttons {
    flex-direction: column;
  }
  
  .control-buttons button {
    width: 100%;
  }
  
  .time-input {
    flex-wrap: wrap;
  }
}
</style>